import { useState, useEffect } from 'react';
import { Settings, Play, Check, Volume2, Music } from 'lucide-react';
import { VideoService, FileService } from '@/services';
import { AudioFormat } from '@/services/VideoService';
import Button from '@/components/common/Button';
import FileUploader from '@/components/common/FileUploader';

interface AudioExtractorProps {
  onClose?: () => void;
}

const AudioExtractor: React.FC<AudioExtractorProps> = ({ onClose }) => {
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [audioFormat, setAudioFormat] = useState('mp3');
  const [bitrate, setBitrate] = useState(192);
  const [sampleRate, setSampleRate] = useState<number | undefined>(44100);
  const [audioFormats, setAudioFormats] = useState<AudioFormat[]>([]);
  const [isProcessing, setIsProcessing] = useState(false);
  const [progress, setProgress] = useState(0);
  const [results, setResults] = useState<any[]>([]);

  useEffect(() => {
    loadAudioFormats();
  }, []);

  const loadAudioFormats = async () => {
    try {
      const formats = await VideoService.getSupportedAudioFormats();
      setAudioFormats(formats);
    } catch (error) {
      console.error('加载音频格式失败:', error);
    }
  };

  const handleFilesSelected = (files: File[]) => {
    setSelectedFiles(files);
  };

  const handleExtract = async () => {
    if (selectedFiles.length === 0) return;

    setIsProcessing(true);
    setProgress(0);
    setResults([]);

    try {
      // Extract parameters are handled by the backend service
      // audio_format: audioFormat,
      // bitrate,
      // sample_rate: sampleRate

      // 模拟提取过程
      for (let i = 0; i < selectedFiles.length; i++) {
        const file = selectedFiles[i];
        const currentProgress = (i / selectedFiles.length) * 100;
        setProgress(currentProgress);

        // 在实际实现中，这里会调用 Tauri 后端
        await new Promise(resolve => setTimeout(resolve, 1500));

        const audioSize = Math.round(file.size * 0.1); // 模拟音频文件大小

        setResults(prev => [
          ...prev,
          {
            id: i,
            fileName: file.name,
            audioFileName: `${file.name.split('.')[0]}.${audioFormat}`,
            status: 'completed',
            audioSize,
            duration: '2秒',
            format: audioFormat.toUpperCase(),
          },
        ]);

        setProgress(((i + 1) / selectedFiles.length) * 100);
      }

      setIsProcessing(false);
    } catch (error) {
      console.error('音频提取失败:', error);
      setIsProcessing(false);
    }
  };

  const bitratePresets = [
    { label: '低质量', value: 128, description: '适合语音和背景音乐' },
    { label: '标准质量', value: 192, description: '平衡音质和文件大小' },
    { label: '高质量', value: 256, description: '适合音乐欣赏' },
    { label: '极高品质', value: 320, description: '接近CD音质' },
  ];

  const sampleRatePresets = [
    { label: 'CD质量', value: 44100, description: '44.1kHz - 标准CD音质' },
    { label: '专业质量', value: 48000, description: '48kHz - 专业音频标准' },
    { label: '高保真', value: 96000, description: '96kHz - 高保真音频' },
    { label: '工作室质量', value: 192000, description: '192kHz - 工作室级别' },
  ];

  return (
    <div className='max-w-6xl mx-auto p-6 space-y-8'>
      {/* Header */}
      <div className='flex items-center justify-between'>
        <div>
          <h1 className='text-3xl font-bold text-gray-900'>音频提取</h1>
          <p className='text-gray-600 mt-2'>从视频文件中提取高质量音频，支持多种音频格式输出</p>
        </div>
        <div className='flex gap-3'>
          <Button variant='secondary' onClick={onClose}>
            返回
          </Button>
        </div>
      </div>

      <div className='grid grid-cols-1 lg:grid-cols-3 gap-8'>
        {/* Left Panel - File Selection */}
        <div className='lg:col-span-2 space-y-6'>
          {/* File Upload */}
          <div className='card p-6'>
            <h2 className='text-xl font-semibold text-gray-900 mb-4'>选择视频文件</h2>
            <FileUploader
              maxFiles={10}
              accept='.mp4,.avi,.mov,.mkv,.wmv,.flv,.webm'
              onFilesSelected={handleFilesSelected}
            />

            {selectedFiles.length > 0 && (
              <div className='mt-4 space-y-2'>
                <h3 className='text-sm font-medium text-gray-900'>
                  已选文件 ({selectedFiles.length})
                </h3>
                {selectedFiles.map((file, index) => (
                  <div
                    key={index}
                    className='flex items-center justify-between p-2 bg-gray-50 rounded'
                  >
                    <div className='flex items-center gap-2'>
                      <Volume2 className='w-4 h-4 text-gray-500' />
                      <span className='text-sm text-gray-700 truncate'>{file.name}</span>
                    </div>
                    <span className='text-xs text-gray-500'>
                      {FileService.formatFileSize(file.size)}
                    </span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Processing Section */}
          {isProcessing && (
            <div className='card p-6'>
              <h2 className='text-xl font-semibold text-gray-900 mb-4'>正在提取音频...</h2>
              <div className='space-y-4'>
                <div className='flex items-center justify-between'>
                  <span className='text-sm text-gray-700'>整体进度</span>
                  <span className='text-sm font-medium text-blue-600'>{Math.round(progress)}%</span>
                </div>
                <div className='w-full bg-gray-200 rounded-full h-2'>
                  <div
                    className='bg-blue-600 h-2 rounded-full transition-all duration-300'
                    style={{ width: `${progress}%` }}
                  />
                </div>

                {/* Current File Info */}
                {progress < 100 && (
                  <div className='flex items-center gap-2 p-2 bg-blue-50 rounded'>
                    <Music className='w-4 h-4 text-blue-600' />
                    <span className='text-sm text-blue-700'>
                      正在提取:{' '}
                      {selectedFiles[Math.floor(progress / (100 / selectedFiles.length))]?.name}
                    </span>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Results Section */}
          {results.length > 0 && (
            <div className='card p-6'>
              <h2 className='text-xl font-semibold text-gray-900 mb-4'>提取结果</h2>
              <div className='space-y-3'>
                {results.map(result => (
                  <div
                    key={result.id}
                    className='p-4 bg-green-50 border border-green-200 rounded-lg'
                  >
                    <div className='flex items-center justify-between mb-3'>
                      <div className='flex items-center gap-2'>
                        <Check className='w-5 h-5 text-green-600' />
                        <div>
                          <p className='text-sm font-medium text-gray-900'>{result.fileName}</p>
                          <p className='text-xs text-gray-500'>→ {result.audioFileName}</p>
                        </div>
                      </div>
                      <span className='text-xs text-green-600 font-medium'>完成</span>
                    </div>

                    <div className='grid grid-cols-2 gap-4 text-sm'>
                      <div>
                        <span className='text-gray-500'>音频格式:</span>
                        <span className='ml-2 font-medium'>{result.format}</span>
                      </div>
                      <div>
                        <span className='text-gray-500'>文件大小:</span>
                        <span className='ml-2 font-medium text-green-600'>
                          {FileService.formatFileSize(result.audioSize)}
                        </span>
                      </div>
                      <div>
                        <span className='text-gray-500'>比特率:</span>
                        <span className='ml-2 font-medium'>{bitrate}kbps</span>
                      </div>
                      <div>
                        <span className='text-gray-500'>处理时间:</span>
                        <span className='ml-2 font-medium'>{result.duration}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Right Panel - Settings */}
        <div className='space-y-6'>
          {/* Audio Settings */}
          <div className='card p-6'>
            <div className='flex items-center gap-2 mb-4'>
              <Settings className='w-5 h-5 text-gray-600' />
              <h3 className='text-lg font-semibold text-gray-900'>音频设置</h3>
            </div>

            <div className='space-y-4'>
              {/* Audio Format */}
              <div>
                <label className='block text-sm font-medium text-gray-700 mb-2'>音频格式</label>
                <select
                  value={audioFormat}
                  onChange={e => setAudioFormat(e.target.value)}
                  className='w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent'
                >
                  {audioFormats.map(format => (
                    <option key={format.extension} value={format.extension}>
                      {format.name} (.{format.extension})
                    </option>
                  ))}
                </select>
              </div>

              {/* Bitrate Settings */}
              <div>
                <label className='block text-sm font-medium text-gray-700 mb-2'>音频比特率</label>
                <div className='space-y-2'>
                  {bitratePresets.map(preset => (
                    <label
                      key={preset.value}
                      className='flex items-center gap-3 p-2 hover:bg-gray-50 rounded cursor-pointer'
                    >
                      <input
                        type='radio'
                        name='bitrate'
                        value={preset.value}
                        checked={bitrate === preset.value}
                        onChange={() => setBitrate(preset.value)}
                        className='text-blue-600 focus:ring-blue-500'
                      />
                      <div>
                        <span className='text-sm font-medium text-gray-900'>{preset.label}</span>
                        <p className='text-xs text-gray-500'>{preset.description}</p>
                      </div>
                    </label>
                  ))}
                </div>
              </div>

              {/* Sample Rate Settings */}
              <div>
                <label className='block text-sm font-medium text-gray-700 mb-2'>采样率</label>
                <div className='space-y-2'>
                  {sampleRatePresets.map(preset => (
                    <label
                      key={preset.value}
                      className='flex items-center gap-3 p-2 hover:bg-gray-50 rounded cursor-pointer'
                    >
                      <input
                        type='radio'
                        name='sampleRate'
                        value={preset.value}
                        checked={sampleRate === preset.value}
                        onChange={() => setSampleRate(preset.value)}
                        className='text-blue-600 focus:ring-blue-500'
                      />
                      <div>
                        <span className='text-sm font-medium text-gray-900'>{preset.label}</span>
                        <p className='text-xs text-gray-500'>{preset.description}</p>
                      </div>
                    </label>
                  ))}
                </div>
              </div>

              {/* Audio Quality Info */}
              <div className='p-3 bg-blue-50 border border-blue-200 rounded'>
                <div className='flex items-center gap-2 mb-2'>
                  <Volume2 className='w-4 h-4 text-blue-600' />
                  <span className='text-sm font-medium text-blue-900'>音质信息</span>
                </div>
                <div className='text-xs text-blue-700 space-y-1'>
                  <div>格式: {audioFormat.toUpperCase()}</div>
                  <div>比特率: {bitrate} kbps</div>
                  <div>采样率: {sampleRate ? `${sampleRate / 1000} kHz` : '自动'}</div>
                  <div>
                    音质:{' '}
                    {bitrate >= 320
                      ? '极高'
                      : bitrate >= 256
                        ? '高'
                        : bitrate >= 192
                          ? '标准'
                          : '基础'}
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Action Buttons */}
          <div className='card p-6'>
            <Button
              variant='primary'
              size='lg'
              icon={<Play className='w-5 h-5' />}
              onClick={handleExtract}
              disabled={selectedFiles.length === 0 || isProcessing}
              className='w-full justify-center'
            >
              {isProcessing ? '提取中...' : '开始提取'}
            </Button>

            <div className='mt-4 text-center text-sm text-gray-500'>
              {selectedFiles.length > 0 ? (
                <div>
                  <p>将提取 {selectedFiles.length} 个音频文件</p>
                  <p className='text-xs mt-1'>
                    格式: {audioFormat.toUpperCase()} | 比特率: {bitrate}kbps
                  </p>
                </div>
              ) : (
                <p>请先选择要提取音频的视频文件</p>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AudioExtractor;
